#include "../include/ThreadPool.hpp"
#include "../include/Thread.hpp"
#include <unistd.h>

wd::ThreadPool::ThreadPool(int threadNum,int queSize)
:_threads()
,_taskque(queSize)
,_threadNum(threadNum)
,_queSize(queSize)
,_isExit(false)
{
    _threads.reserve(10);
}

void wd::ThreadPool::start(){
    for(int i = 0;i < _threadNum; ++i){
        unique_ptr<Thread> up(new wd::Thread(std::bind(&ThreadPool::doTask,this)));
        _threads.push_back(std::move(up));
    }

    for(auto &pthread : _threads){
        pthread->start(); 
    }
}

void wd::ThreadPool::stop(){
    while(!_taskque.empty()){
        sleep(1);
    } 

    _isExit = true;
    _taskque.wakeup();
    for(auto & pthread : _threads){
        pthread->join();
    }
}

void wd::ThreadPool::addTask(ElemType && e){
    if(e){
        _taskque.push(e);
    }
}

void wd::ThreadPool::doTask(){
        while(!_isExit){
            ElemType ptask =  _taskque.pop(); 
            if(ptask){
                ptask();
            }
        }
}

